package org.example.download;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class DownloadManager {
    private String url;
    private String directoryPath;
    private String fileName;
    private int threadCount;

    public DownloadManager(String url, String directoryPath, String fileName, int threadCount) {
        this.url = url;
        this.directoryPath = directoryPath;
        this.fileName = fileName;
        this.threadCount = threadCount;
    }

    public void startDownload() throws IOException, InterruptedException {
        long fileSize = HttpUtils.getFileSize(url);
        String filePath = directoryPath + File.separator + fileName;
        FileUtils.createFileIfNotExists(filePath, fileSize);
        long partSize = fileSize / threadCount;

        ExecutorService executor = Executors.newFixedThreadPool(threadCount);
        for (int i = 0; i < threadCount; i++) {
            long startIndex = i * partSize;
            long endIndex = (i == threadCount - 1) ? fileSize - 1 : (startIndex + partSize - 1);
            executor.execute(new DownloadThread(i, startIndex, endIndex, url, filePath));
        }
        executor.shutdown(); // Disable new tasks from being submitted

        // Wait a while for existing tasks to terminate
        if (!executor.awaitTermination(15, TimeUnit.SECONDS)) {
            // Cancel currently running tasks
            executor.shutdownNow();
            // Wait a while for tasks to respond to being cancelled
            if (!executor.awaitTermination(15, TimeUnit.SECONDS))
                System.err.println("Pool did not terminate");
        }
    }
}